package com.emmmya.ocs.modules.system.utils;

import com.alibaba.fastjson.JSON;
import com.emmmya.ocs.modules.system.service.UserService;
import com.emmmya.ocs.config.redis.RedisManager;
import com.emmmya.ocs.modules.system.entity.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

/**
 * @description: 获取当前登录的user、当前用户的token等
 * @author: 咕噜肉IT小店-黑医
 * @createDate: 2020-12-10
 * @version: 1.0
 */
@Component
public class UserUtils {
    @Autowired
    UserService userService;
    @Autowired
    RedisManager redisManager;

    public User getCurrentUser(){
        Session session = SecurityUtils.getSubject().getSession();
        Object currentUser = session.getAttribute("currentUser");
        //坑，如果role设置null，则中间表h_user_role会清空用户的角色信息。
        if(currentUser == null){
            return null;
        }
        //解决热部署问题。
        if(currentUser instanceof User) {
            return (User) currentUser;
        }else {
           return JSON.parseObject(JSON.toJSON(currentUser).toString(), User.class);
        }
    }

    public String getCurrentUserToken(){
        String token = (String)redisManager.get((String) SecurityUtils.getSubject().getPrincipal());
        return token;
    }

    public String getCurrentUserName(){
        return getCurrentUser().getUsername();
    }


    public boolean userHasRole(String roleName){
        return SecurityUtils.getSubject().hasRole(roleName);
    }

    public boolean userHasAnyOneRole(String[] roleNames){
        return userHasAnyOneRole(Arrays.asList(roleNames));
    }

    public boolean userHasAnyOneRole(List<String> roleNames){
        boolean[] results = SecurityUtils.getSubject().hasRoles(roleNames);
        for (boolean result : results) {
            if(result){
                return true;
            }
        }

        return false;
    }

    public boolean userHasAllRoles(String[] roleNames){
        return userHasAllRoles(Arrays.asList(roleNames));
    }

    public boolean userHasAllRoles(List<String> roleNames){
        boolean[] results = SecurityUtils.getSubject().hasRoles(roleNames);
        for (boolean result : results) {
            if(!result){
                return false;
            }
        }
        return true;
    }



}
